#!/usr/bin/enr/python3
# -*- coding: utf-8 -*-
# -------------------------------
# @Author : hurong
# @File : 1105_p02装饰器.py
# @Time : 2023/11/16 16:09
# -------------------------------

# 装饰器就是一个特殊的闭包函数的定义形式
# 1. 外函数中必须定义一个内函数
# 2. 内函数必须要使用外函数的局部变量
# 3. 外函数必须要返回内函数的引用
# 装饰器：给现有的函数，在不更改函数功能以及函数调用的前提下，为这个函数增加额外的功能
import time


def outer(func):    # 可以作为装饰器的闭包函数
    def inner():
        # 打印
        print("被装饰函数执行前的装饰代码")
        func()    # 使用外函数的局部变量
        print("被装饰函数执行后的装饰代码")
    return  inner

@outer    # 装饰器
def show():
    print("Show Run...")

# 调用
show()
print(show)
# 有装饰器，执行打印show的结果
# <function outer.<locals>.inner at 0x000001E9EBC294C0>
# 没有装饰器的，执行打印show的结果
#<function show at 0x0000015479D58EE0>

# 装饰过程原理
# show = outer(show)
# show = inner
# show = outer.<locals>.inner

"""print("*" * 20 + "实例二" +"*" * 20)
def mysum():
    n = 0
    start = time.time()
    for i in range(1000001):
        n += 1
    print(n)
    # 求耗时
    stop = time.time()
    print(f"耗时{stop - start} 秒")

mysum()"""

"""print("*" * 20 + "实例三,进阶写法" +"*" * 20)

def countTime(func):
    start = time.time()
    func()
    # 求耗时
    stop = time.time()
    print(f"耗时{stop - start} 秒")


def mysum():
    n = 0
    for i in range(1000001):
        n += 1
    print(n)

countTime(mysum)
mysum()"""

# print(f"*" * 20 + "实力四，装饰器写法" + "*" * 20)
# def count_time(func):
#     def inner():
#         start = time.time()
#         func()
#         stop = time.time()
#         print(f"耗时{stop - start} 秒")
#     return  inner
#
# @count_time    # 写此装饰器函数，则执行时，会有装饰器函数中的功能作用
# def mysum():
#     n = 0
#     for i in range(1000001):
#         n += 1
#     print(n)
#
# def show():
#     print("show run...")
#
# mysum()
# show()

print(f"*" * 20 + "实例五，通用装饰器" + "*" * 20)
def count_time(func):
    def inner(*args, **kwargs):    # 50005000
        start = time.time()
        result = func(*args, **kwargs)
        stop = time.time()
        print(f"耗时{stop - start} 秒")
        return  result
    return  inner

@count_time    # 写此装饰器函数，则执行时，会有装饰器函数中的功能作用
def mysum():
    n = 0
    for i in range(100001):
        n += 1
    return n  # 回到调用处


@count_time
def show(n):
    for i in range(n):
        print("show run...")


@count_time
def show2(n, msg):
    for i in range(n):
        print(msg)

a = mysum()
print(a)
show(5)
show2(3, 'hello')